/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainWindow.java
 *
 * Created on 20.10.2011, 15:14:43
 */
package view;

/**
 *
 * @author zhenia
 */
import data.model.Route;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import logic.business.DataEditor;
import logic.business.FileManipulator;
import logic.business.exceptions.ConstraintException;
import logic.business.exceptions.MalformedDataException;
import logic.optimization.Optimizer;
import view.MyTableModel;

class ExtensionFileFilter extends FileFilter {

    String description;
    String extensions[];

    public ExtensionFileFilter(String description, String extension) {
        this(description, new String[]{extension});
    }

    public ExtensionFileFilter(String description, String extensions[]) {
        if (description == null) {
            this.description = extensions[0] + "{ " + extensions.length + "} ";
        } else {
            this.description = description;
        }
        this.extensions = (String[]) extensions.clone();
        toLower(this.extensions);
    }

    private void toLower(String array[]) {
        for (int i = 0, n = array.length; i < n; i++) {
            array[i] = array[i].toLowerCase();
        }
    }

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public boolean accept(File file) {
        if (file.isDirectory()) {
            return true;
        } else {
            String path = file.getAbsolutePath().toLowerCase();
            for (int i = 0, n = extensions.length; i < n; i++) {
                String extension = extensions[i];
                if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == '.')) {
                    return true;
                }
            }
        }
        return false;
    }
}

public class MainWindow extends javax.swing.JFrame {

    // FileManipulator fileManipulaton = new FileManipulator();
    FileManipulator fileManipulator = FileManipulator.getInstance();
    File selectedFile;
    private DataEditor dataEditor;
    Optimizer optimizer;
    private NewRouteDialog newRouteDialog = null;
    private NewAirportDialog newAirportDialog;
    private NewAirplaneDialog newAirplaneDialog;
    private NewFlightDialog newFlightDialog;
    private NewAirlineDialog newAirlineDialog;
    private NewCityDialog newCityDialog;
    private TableModel MyTableModel;

    /** Creates new form MainWindow */
    public MainWindow() {
        initComponents();
        about.setVisible(true);
        workPlace.setVisible(false);
//        airline.setVisible(false);
        //      route.setVisible(false);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        popup = new javax.swing.JPopupMenu();
        delete = new javax.swing.JMenuItem();
        edit = new javax.swing.JMenuItem();
        jToolBar1 = new javax.swing.JToolBar();
        New = new javax.swing.JButton();
        Open = new javax.swing.JButton();
        Save = new javax.swing.JButton();
        Optimize = new javax.swing.JButton();
        about = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        workPlace = new javax.swing.JPanel();
        optimize = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        optimized = new javax.swing.JTextArea();
        jToolBar2 = new javax.swing.JToolBar();
        newAirline = new javax.swing.JButton();
        newRoute = new javax.swing.JButton();
        newAirport = new javax.swing.JButton();
        newAirplane = new javax.swing.JButton();
        newFlight = new javax.swing.JButton();
        newPlace = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        info = new javax.swing.JTextArea();
        infoLabel = new javax.swing.JLabel();
        optimalizationResultLabel = new javax.swing.JLabel();
        exportButton = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jTabbedPane3 = new javax.swing.JTabbedPane();
        jTabbedPane4 = new javax.swing.JTabbedPane();
        jTabbedPane5 = new javax.swing.JTabbedPane();
        jTabbedPane6 = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        file = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        open = new javax.swing.JMenuItem();
        save = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        jLabel1.setText("jLabel1");
        jLabel1.setName("jLabel1"); // NOI18N

        popup.setName("popup"); // NOI18N

        delete.setText("Delete");
        delete.setName("delete"); // NOI18N
        popup.add(delete);

        edit.setText("Edit");
        edit.setName("edit"); // NOI18N
        popup.add(edit);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Pegasus Optimalizator");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setName("jToolBar1"); // NOI18N

        New.setText("New");
        New.setFocusable(false);
        New.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        New.setName("New"); // NOI18N
        New.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        New.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NewActionPerformed(evt);
            }
        });
        jToolBar1.add(New);

        Open.setText("Open");
        Open.setEnabled(false);
        Open.setFocusable(false);
        Open.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Open.setName("Open"); // NOI18N
        Open.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenActionPerformed(evt);
            }
        });
        jToolBar1.add(Open);

        Save.setText("Save");
        Save.setEnabled(false);
        Save.setFocusable(false);
        Save.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Save.setName("Save"); // NOI18N
        Save.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveActionPerformed(evt);
            }
        });
        jToolBar1.add(Save);

        Optimize.setText("Optimize");
        Optimize.setEnabled(false);
        Optimize.setFocusable(false);
        Optimize.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Optimize.setName("Optimize"); // NOI18N
        Optimize.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Optimize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OptimizeActionPerformed(evt);
            }
        });
        jToolBar1.add(Optimize);

        getContentPane().add(jToolBar1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 25));

        about.setName("about"); // NOI18N

        jLabel2.setText("Vitame vas v programu Pegasus Optimizator, slouzici k optimalizaci letovych linek.");
        jLabel2.setName("jLabel2"); // NOI18N

        javax.swing.GroupLayout aboutLayout = new javax.swing.GroupLayout(about);
        about.setLayout(aboutLayout);
        aboutLayout.setHorizontalGroup(
            aboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(aboutLayout.createSequentialGroup()
                .addComponent(jLabel2)
                .addContainerGap(37, Short.MAX_VALUE))
        );
        aboutLayout.setVerticalGroup(
            aboutLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(aboutLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(about, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 20, -1, -1));

        workPlace.setName("workPlace"); // NOI18N

        optimize.setText("Optimize");
        optimize.setEnabled(false);
        optimize.setName("optimize"); // NOI18N
        optimize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optimizeActionPerformed(evt);
            }
        });

        jButton2.setText("Import XML");
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        optimized.setColumns(20);
        optimized.setEditable(false);
        optimized.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
        optimized.setRows(5);
        optimized.setText("Ratings...");
        optimized.setName("optimized"); // NOI18N
        jScrollPane2.setViewportView(optimized);

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);
        jToolBar2.setName("jToolBar2"); // NOI18N

        newAirline.setText("New Airline");
        newAirline.setEnabled(false);
        newAirline.setFocusable(false);
        newAirline.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newAirline.setName("newAirline"); // NOI18N
        newAirline.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newAirline.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newAirlineActionPerformed(evt);
            }
        });
        jToolBar2.add(newAirline);

        newRoute.setText("New Route");
        newRoute.setEnabled(false);
        newRoute.setFocusable(false);
        newRoute.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newRoute.setName("newRoute"); // NOI18N
        newRoute.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newRoute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newRouteActionPerformed(evt);
            }
        });
        jToolBar2.add(newRoute);

        newAirport.setText("New Airport");
        newAirport.setEnabled(false);
        newAirport.setFocusable(false);
        newAirport.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newAirport.setName("newAirport"); // NOI18N
        newAirport.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newAirport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newAirportActionPerformed(evt);
            }
        });
        jToolBar2.add(newAirport);

        newAirplane.setText("New Airplane");
        newAirplane.setEnabled(false);
        newAirplane.setFocusable(false);
        newAirplane.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newAirplane.setName("newAirplane"); // NOI18N
        newAirplane.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newAirplane.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newAirplaneActionPerformed(evt);
            }
        });
        jToolBar2.add(newAirplane);

        newFlight.setText("New Flight");
        newFlight.setEnabled(false);
        newFlight.setFocusable(false);
        newFlight.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newFlight.setName("newFlight"); // NOI18N
        newFlight.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newFlight.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newFlightActionPerformed(evt);
            }
        });
        jToolBar2.add(newFlight);

        newPlace.setText("New Place");
        newPlace.setEnabled(false);
        newPlace.setFocusable(false);
        newPlace.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newPlace.setName("newPlace"); // NOI18N
        newPlace.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newPlace.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newPlaceActionPerformed(evt);
            }
        });
        jToolBar2.add(newPlace);

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        info.setColumns(20);
        info.setEditable(false);
        info.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
        info.setRows(5);
        info.setText("Info...");
        info.setName("info"); // NOI18N
        jScrollPane3.setViewportView(info);

        infoLabel.setText("Info about new possible routes");
        infoLabel.setName("infoLabel"); // NOI18N

        optimalizationResultLabel.setText("New ratings");
        optimalizationResultLabel.setName("optimalizationResultLabel"); // NOI18N

        exportButton.setText("Export");
        exportButton.setToolTipText("Export to CSV");
        exportButton.setEnabled(false);
        exportButton.setName("exportButton"); // NOI18N
        exportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportButtonActionPerformed(evt);
            }
        });

        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object[][]{
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null}

            },
            new String[]{
                "Airline", "Route", "Departure time", "Arrival time", "Rating", "Capacity", "Airplane", "Flight"
            }) {

                boolean[] canEdit = new boolean[]{
                    false, true, false, false, true, true, true, true
                };

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit[columnIndex];
                }
            });
            table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
            table.setName("table"); // NOI18N
            table.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    tableMouseClicked(evt);
                }
            });
            jScrollPane1.setViewportView(table);

            jTabbedPane1.addTab("Flights", jScrollPane1);

            jTabbedPane2.setName("jTabbedPane2"); // NOI18N
            jTabbedPane1.addTab("Routes", jTabbedPane2);

            jTabbedPane3.setName("jTabbedPane3"); // NOI18N
            jTabbedPane1.addTab("Airlines", jTabbedPane3);

            jTabbedPane4.setName("jTabbedPane4"); // NOI18N
            jTabbedPane1.addTab("Airplanes", jTabbedPane4);

            jTabbedPane5.setName("jTabbedPane5"); // NOI18N
            jTabbedPane1.addTab("Airports", jTabbedPane5);

            jTabbedPane6.setName("jTabbedPane6"); // NOI18N
            jTabbedPane1.addTab("Cities", jTabbedPane6);

            javax.swing.GroupLayout workPlaceLayout = new javax.swing.GroupLayout(workPlace);
            workPlace.setLayout(workPlaceLayout);
            workPlaceLayout.setHorizontalGroup(
                workPlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jToolBar2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 720, Short.MAX_VALUE)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, workPlaceLayout.createSequentialGroup()
                    .addContainerGap(558, Short.MAX_VALUE)
                    .addComponent(exportButton, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(optimize)
                    .addContainerGap())
                .addGroup(workPlaceLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(optimalizationResultLabel)
                    .addContainerGap(653, Short.MAX_VALUE))
                .addGroup(workPlaceLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(infoLabel)
                    .addContainerGap(561, Short.MAX_VALUE))
                .addGroup(workPlaceLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jButton2)
                    .addContainerGap(623, Short.MAX_VALUE))
                .addGroup(workPlaceLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(workPlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 700, Short.MAX_VALUE))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            workPlaceLayout.setVerticalGroup(
                workPlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, workPlaceLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(infoLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(25, 25, 25)
                    .addComponent(optimalizationResultLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(54, 54, 54)
                    .addGroup(workPlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(optimize)
                        .addComponent(exportButton))
                    .addContainerGap())
            );

            getContentPane().add(workPlace, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, -1, -1));

            jMenuBar1.setName("jMenuBar1"); // NOI18N

            file.setText("File");
            file.setName("file"); // NOI18N
            file.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    fileActionPerformed(evt);
                }
            });

            jMenuItem1.setText("New");
            jMenuItem1.setName("jMenuItem1"); // NOI18N
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem1ActionPerformed(evt);
                }
            });
            file.add(jMenuItem1);

            open.setText("Open");
            open.setEnabled(false);
            open.setName("open"); // NOI18N
            open.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    openActionPerformed(evt);
                }
            });
            file.add(open);

            save.setText("Save");
            save.setEnabled(false);
            save.setName("Save"); // NOI18N
            save.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    saveActionPerformed(evt);
                }
            });
            file.add(save);

            jMenuItem4.setText("Exit");
            jMenuItem4.setName("jMenuItem4"); // NOI18N
            jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenuItem4ActionPerformed(evt);
                }
            });
            file.add(jMenuItem4);

            jMenuBar1.add(file);

            jMenu2.setText("Edit");
            jMenu2.setName("jMenu2"); // NOI18N
            jMenuBar1.add(jMenu2);

            setJMenuBar(jMenuBar1);

            pack();
        }// </editor-fold>//GEN-END:initComponents

    private void NewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewActionPerformed
        // popisProgramu.setVisible(false);
        //    imageLabel.setVisible(false);
        about.setVisible(false);
        workPlace.setVisible(true);
        open.setEnabled(true);
        Open.setEnabled(true);

    }//GEN-LAST:event_NewActionPerformed

    private void OpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenActionPerformed
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setVisible(true);
        FileFilter XMLFilter = new ExtensionFileFilter(null, new String[]{"XML"});

        fileChooser.addChoosableFileFilter(XMLFilter);
        int status = fileChooser.showOpenDialog(null);
        if (status == JFileChooser.APPROVE_OPTION) {
            try {
                selectedFile = fileChooser.getSelectedFile();
                dataEditor = fileManipulator.readFile(selectedFile.getName());
                table.setModel(new MyTableModel(dataEditor.getAllFlights()));
                TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());
                table.setRowSorter(sorter);
                enableItems();
                exportButton.setEnabled(false);

            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this,
                        "File is corrupted",
                        "Warning",
                        JOptionPane.WARNING_MESSAGE);
            }
        } else if (status == JFileChooser.CANCEL_OPTION) {
            System.out.println("canceled");
        }


    }//GEN-LAST:event_OpenActionPerformed
    private void enableItems() {
        newAirline.setEnabled(true);
        newAirplane.setEnabled(true);
        newAirport.setEnabled(true);
        newFlight.setEnabled(true);
        newPlace.setEnabled(true);
        newRoute.setEnabled(true);
        optimize.setEnabled(true);
        Optimize.setEnabled(true);
        Save.setEnabled(true);
        save.setEnabled(true);
    }

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        about.setVisible(false);
        workPlace.setVisible(true);

    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed
        // TODO add your handling code here:
        OpenActionPerformed(evt);

    }//GEN-LAST:event_openActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void newAirlineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newAirlineActionPerformed
        this.newAirlineDialog = new NewAirlineDialog(dataEditor);
        // создаём объект дочернего окна, передавая в конструктор this-ссылку - т.о., именно это окно становится для нового родительским
        if (this.newAirlineDialog.execute()) {
            // действия при нажатии клавиши ОК - в моём случае извлечение данных, введёных пользователем в поля дочернего окошка; в случае с тремя и более кнопками, можно применить конструкцию switch (this.dialog.execute()) - соответственно, методу execute обеспечить соответствующую разновидность возврата более двух значений
            // здесь же прописывается считывание нужных результатов, введённых пользователем, используя функции get, заблаговременно прописанные вами в класе дочернего окна
        } else {
            // действия при нажатии на клавишу отмены
        }


    }//GEN-LAST:event_newAirlineActionPerformed

    private void newRouteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newRouteActionPerformed
        this.newRouteDialog = new NewRouteDialog(dataEditor);
        // создаём объект дочернего окна, передавая в конструктор this-ссылку - т.о., именно это окно становится для нового родительским
        if (this.newRouteDialog.execute()) {
            // String[] route = this.newRouteDialog.getCurrentRoute();

            dataEditor = this.newRouteDialog.getDataEditor();

            //  this.dataEditor.addNewRoute(route[0], route[1], route[2], route[3], route[4], route[5]);
            // здесь же прописывается считывание нужных результатов, введённых пользователем, используя функции get, заблаговременно прописанные вами в класе дочернего окна
            // здесь же прописывается считывание нужных результатов, введённых пользователем, используя функции get, заблаговременно прописанные вами в класе дочернего окна


        } else {
            // действия при нажатии на клавишу отмены
        }
    }//GEN-LAST:event_newRouteActionPerformed

    private void newAirportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newAirportActionPerformed
        this.newAirportDialog = new NewAirportDialog(dataEditor);
        // создаём объект дочернего окна, передавая в конструктор this-ссылку - т.о., именно это окно становится для нового родительским
        if (this.newAirportDialog.execute()) {
            // действия при нажатии клавиши ОК - в моём случае извлечение данных, введёных пользователем в поля дочернего окошка; в случае с тремя и более кнопками, можно применить конструкцию switch (this.dialog.execute()) - соответственно, методу execute обеспечить соответствующую разновидность возврата более двух значений
            // здесь же прописывается считывание нужных результатов, введённых пользователем, используя функции get, заблаговременно прописанные вами в класе дочернего окна
        } else {
            // действия при нажатии на клавишу отмены
        }
    }//GEN-LAST:event_newAirportActionPerformed

    private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
        // TODO add your handling code here:
        SaveActionPerformed(evt);
    }//GEN-LAST:event_saveActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        OpenActionPerformed(evt);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void fileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_fileActionPerformed

    private void SaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveActionPerformed
        // TODO add your handling code here:
        fileManipulator.saveFile(selectedFile.getName());
        fileManipulator.saveFile();

    }//GEN-LAST:event_SaveActionPerformed

    private void optimizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optimizeActionPerformed
        // TODO add your handling code here:
        /////OPTIMIZACE POMOCI DATAEDITORU A METODY OPTIMIZE

        dataEditor.optimize();
        dataEditor.info();
        table.setModel(new MyTableModel(dataEditor.getAllFlights()));
        info.setText("");
        optimized.setText("");
        exportButton.setEnabled(true);

        for (String a : dataEditor.info()) {

            info.append(a + "\n");
            //dataEditor.addNewRoute(a.getId(), a.getFrequency(),a.getRating(), a.getWeeklyPassengers(), a.getDepartureAirport(), a.getArrivalAirport());

        }


        for (Route a : dataEditor.getOptimizedRoutes()) {

            optimized.append(a.toString() + " : " + a.getRating() + "\n");
            //dataEditor.addNewRoute(a.getId(), a.getFrequency(),a.getRating(), a.getWeeklyPassengers(), a.getDepartureAirport(), a.getArrivalAirport());

        }


    }//GEN-LAST:event_optimizeActionPerformed

    private void OptimizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OptimizeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_OptimizeActionPerformed

    private void newAirplaneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newAirplaneActionPerformed
        this.newAirplaneDialog = new NewAirplaneDialog(dataEditor);
        // создаём объект дочернего окна, передавая в конструктор this-ссылку - т.о., именно это окно становится для нового родительским
        if (this.newAirplaneDialog.execute()) {
            dataEditor = this.newAirplaneDialog.getDataEditor();

        } else {
            // действия при нажатии на клавишу отмены
        }
    }//GEN-LAST:event_newAirplaneActionPerformed

    private void newFlightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newFlightActionPerformed
        this.newFlightDialog = new NewFlightDialog(dataEditor);
        // создаём объект дочернего окна, передавая в конструктор this-ссылку - т.о., именно это окно становится для нового родительским
        if (this.newFlightDialog.execute()) {
            // действия при нажатии клавиши ОК - в моём случае извлечение данных, введёных пользователем в поля дочернего окошка; в случае с тремя и более кнопками, можно применить конструкцию switch (this.dialog.execute()) - соответственно, методу execute обеспечить соответствующую разновидность возврата более двух значений
            // здесь же прописывается считывание нужных результатов, введённых пользователем, используя функции get, заблаговременно прописанные вами в класе дочернего окна
        } else {
            // действия при нажатии на клавишу отмены
        }
    }//GEN-LAST:event_newFlightActionPerformed

    private void newPlaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newPlaceActionPerformed
        // TODO add your handling code here:
        this.newCityDialog = new NewCityDialog(dataEditor);
        // создаём объект дочернего окна, передавая в конструктор this-ссылку - т.о., именно это окно становится для нового родительским
        if (this.newCityDialog.execute()) {
            dataEditor = this.newCityDialog.getDataEditor();

        } else {
            // действия при нажатии на клавишу отмены
        }

    }//GEN-LAST:event_newPlaceActionPerformed

    private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setApproveButtonText("Export");
        fc.setDialogType(JFileChooser.SAVE_DIALOG);
        fc.setDialogTitle("Export to CSV");

        int returnVal = fc.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file2 = fc.getSelectedFile();
            String fileName = file2.getName();
            String path = file2.getPath();
            fileManipulator.exportToCSV(path);
        }
    }//GEN-LAST:event_exportButtonActionPerformed

private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
    if (SwingUtilities.isRightMouseButton(evt)) {
        Point p = evt.getPoint();
        int row = table.rowAtPoint(p);
        ListSelectionModel lsm = table.getSelectionModel();
        lsm.clearSelection();
        lsm.addSelectionInterval(row, row);
        popup.show(table, evt.getX(), evt.getY());
    }
}//GEN-LAST:event_tableMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                        if ("Windows".equals(info.getName())) {
                            javax.swing.UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                } catch (ClassNotFoundException ex) {
                    java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
                } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                    java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
                }
                new MainWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton New;
    private javax.swing.JButton Open;
    private javax.swing.JButton Optimize;
    private javax.swing.JButton Save;
    private javax.swing.JPanel about;
    private javax.swing.JMenuItem delete;
    private javax.swing.JMenuItem edit;
    private javax.swing.JButton exportButton;
    private javax.swing.JMenu file;
    private javax.swing.JTextArea info;
    private javax.swing.JLabel infoLabel;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JTabbedPane jTabbedPane3;
    private javax.swing.JTabbedPane jTabbedPane4;
    private javax.swing.JTabbedPane jTabbedPane5;
    private javax.swing.JTabbedPane jTabbedPane6;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JButton newAirline;
    private javax.swing.JButton newAirplane;
    private javax.swing.JButton newAirport;
    private javax.swing.JButton newFlight;
    private javax.swing.JButton newPlace;
    private javax.swing.JButton newRoute;
    private javax.swing.JMenuItem open;
    private javax.swing.JLabel optimalizationResultLabel;
    private javax.swing.JButton optimize;
    private javax.swing.JTextArea optimized;
    private javax.swing.JPopupMenu popup;
    private javax.swing.JMenuItem save;
    private javax.swing.JTable table;
    private javax.swing.JPanel workPlace;
    // End of variables declaration//GEN-END:variables
}
